import axios from 'axios'
import { Indicator, Toast } from 'mint-ui';
// axios 配置
axios.defaults.timeout = 60000
axios.defaults.baseURL = ''

// if(process.env.NODE_ENV == 'development'){
//   axios.defaults.baseURL = 'http://127.0.0.1'
// }

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  Indicator.open();
  return config;
}, function (error) {

  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  Indicator.close();
  if (res.status >= 200 && res.status < 300) {
    return res
  }
  return Promise.reject(res)
}, (error) => {
  // 网络异常
  Indicator.close();
  Toast('网络异常，请刷新重试');
  return Promise.reject({ message: '网络异常，请刷新重试', err: error })
})

let api = {
  base_target: '/wecastsvr',
  get: function (params = {}, server_part) {
    server_part = server_part || this.base_target

    const suffix = Object.keys(params).map(name => {
      return `${name}=${params[name]}`
    }).join('&')
    const urls = `${server_part}?${suffix}`
    // console.log(urls)
    return new Promise((resolve, reject) => {
      axios.get(urls, params).then(res => {
        if (res.data.returncode != '000000') {
          Toast(res.data.returnmessage)
        }
        resolve(res.data)
      }).catch((error) => {
        reject(error)
      })
    })
  },
  post: function (options = {}, server_part) {
    server_part = server_part || this.base_target

    return new Promise((resolve, reject) => {
      axios.post(server_part, options, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        transformRequest: [function (data) {
          var ret = '';
          for (var key in data) {
            ret += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&';
          }
          return ret
        }]
      }).then(res => {
        resolve(res.data)
      }).catch((error) => {
        reject(error)
      })
    })
  }
}

export default api